<?php
/**
 * 合同控制器
 * @author wangwx 2015-5-7
 */
namespace mybackend\controllers;

use common\services\myhtsq\DocumentService;
use common\services\myhtsq\ErpInterfaceService;
use Yii;
use common\services\myhtsq\ContractService;
use common\entities\myhtsq\ActionCode;
use common\support\CacheManage;
use common\support\ExcelSimpleExport;
use yii\filters\AccessControl;
use common\support\ExcelManage;

class ContractController extends BaseController
{
    protected $_contractService;

    public function __construct($id, $module, ContractService $contractService, $config = [])
    {
        $this->_contractService = $contractService;
        parent::__construct($id, $module, $config);
    }

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['authorization-expired-remind'],
                        'allow' => true,
                    ],
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ]
        ];
    }

    protected function roleAuthRules()
    {
        return [
            'actions' =>
//            [],
                ['AddContract', 'AuditReview', 'CancelContract', 'CancelReview', 'ExportBalanceContractListExecl', 'ImportBalanceContractListExecl',
                    'GetBalanceContractList', 'GetContractBalanceInfo', 'GetContractDocuments', 'GetContractInfo', 'GetContractList', 'GetContractOrganizationInfo',
                    'GetContractRevenue', 'GetReceivableFundName', 'GetSignAchievement', 'SaveSignAchievement', 'SubmitRevenue', 'SubmitReview', 'UpdateContract','CancelConfirmContract',
                    'UpdateContractAccount', 'SaveContractDocuments','ExportContract','GetContractProviders','GetProductType','GetWithdrawFeeRate',
                ],
            'rules' => [
                [
                    'allow' => true,
                    'actionCodeMaps' => [
                        'AddContract' => ActionCode::CONTRACT_MNG,
                        'AuditReview' => ActionCode::CONTRACT_APPROVE,
                        'CancelContract' => ActionCode::CONTRACT_MNG,
                        'CancelReview' => ActionCode::CONTRACT_MNG,
                        'ExportBalanceContractListExecl' => ActionCode::CONTRACT_MNG,
                        'ImportBalanceContractListExecl' => ActionCode::CONTRACT_MNG,
                        'GetBalanceContractList' => ActionCode::CONTRACT_BALANCE_VIEW,
                        'GetContractBalanceInfo' => ActionCode::CONTRACT_VIEW,
                        'GetContractDocuments' => ActionCode::CONTRACT_VIEW,
                        'GetContractInfo' => ActionCode::CONTRACT_VIEW,
                        'GetContractList' => ActionCode::CONTRACT_VIEW,
                        'GetContractOrganizationInfo' => ActionCode::CONTRACT_VIEW,
                        'GetContractRevenue' => ActionCode::CONTRACT_VIEW,
                        'GetReceivableFundName' => ActionCode::CONTRACT_VIEW,
                        'GetSignAchievement' => ActionCode::CONTRACT_VIEW,
                        'SaveSignAchievement' => ActionCode::CONTRACT_MNG,
                        'SubmitRevenue' => ActionCode::CONTRACT_MNG,
                        'SubmitReview' => ActionCode::CONTRACT_MNG,
                        'UpdateContract' => ActionCode::CONTRACT_MNG,
                        'UpdateContractAccount' => ActionCode::CONTRACT_MNG,
                        'CancelConfirmContract' => ActionCode::CONTRACT_MNG,
                        'SaveContractDocuments' => ActionCode::CONTRACT_MNG,
                        'ExportContract'=>ActionCode::CONTRACT_HT,
                        'GetContractProviders'  => ActionCode::CONTRACT_MNG,
                        'GetProductType'        => ActionCode::CONTRACT_MNG,
                        'GetWithdrawFeeRate'    => ActionCode::CONTRACT_MNG
                    ]
                ]
            ]
        ];
    }

    /**
     * 新建合同
     */
    public function actionAddContract()
    {
        $this->exitIfNotPost();
        $contract = $this->getParam('contract', 'post');//合同内容
        $productArr = $this->getParam('product', 'post');//产品数组

        $addition = [
            'business_type_id'  => isset($contract['business_type_id']) ? $contract['business_type_id'] : '',
            'supplier_name'     => isset($contract['supplier_name']) ? $contract['supplier_name'] : '',
            'supplier_id'       => isset($contract['supplier_id']) ? $contract['supplier_id'] : '',
            'activity_name'     => isset($contract['activity_name']) ? $contract['activity_name'] : '',
            'activity_id'       => isset($contract['activity_id']) ? $contract['activity_id'] : '',
            'activity_location' => isset($contract['activity_location']) ? $contract['activity_location'] : '',
        ];

        $data = $this->_contractService->addContract($contract, $productArr, false, $addition);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 更新合同
     */
    public function actionUpdateContract()
    {
        $this->exitIfNotPost();
        $contract = $this->getParam('contract', 'post');//合同内容
        $productArr = $this->getParam('product', 'post');//产品数组
        if (empty($contract['contract_id'])) {//合同id是否为空
            $this->errorParam();
        }

        $addition = [
            'business_type_id'  => isset($contract['business_type_id']) ? $contract['business_type_id'] : '',
            'supplier_name'     => isset($contract['supplier_name']) ? $contract['supplier_name'] : '',
            'supplier_id'       => isset($contract['supplier_id']) ? $contract['supplier_id'] : '',
            'activity_name'     => isset($contract['activity_name']) ? $contract['activity_name'] : '',
            'activity_id'       => isset($contract['activity_id']) ? $contract['activity_id'] : '',
            'activity_location' => isset($contract['activity_location']) ? $contract['activity_location'] : '',
        ];

        $data = $this->_contractService->updateContract($contract, $productArr, $addition);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同基本信息与签约产品信息
     */
    public function actionGetContractInfo($contractId = '')
    {
        if (empty($contractId)) {
            $this->errorParam();
        }
        $data = $this->_contractService->getContractInfo($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 提交合同复核
     */
    public function actionSubmitReview()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');//合同内容
        if (empty($contractId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->submitReview($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 撤销合同复核
     */
    public function actionCancelReview()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');//合同内容
        if (empty($contractId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->cancelReview($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    public function actionCancelConfirmContract(){
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');//合同内容
        if (empty($contractId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->cancelConfirmContract($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 合同复核
     */
    public function actionAuditReview()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');//合同内容
        if (empty($contractId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->auditReview($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 根据性质id,获取帐套公司列表
     * @param string $propertyId 性质id
     * @return array
     */
    public function actionGetContractAccountCompanyList($propertyId = '')
    {
        if (empty($propertyId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->getContractAccountCompanyList($propertyId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 根据性质id,获取签署公司列表
     * @param string $propertyId 性质id
     * @return array
     */
    public function actionGetContractCompanyList($propertyId = '')
    {
        if (empty($propertyId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->getContractCompanyList($propertyId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 作废合同
     */
    public function actionCancelContract()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');//合同内容
        if (empty($contractId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->cancelContract($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 合同列表
     * @param integer $pageIndex 页码
     * @param integer $pageSize 页条数
     * @param string $sortBy 排序字段
     * @param int $status 合同状态  合同状态:0：草稿,1：提交复核,2：已审核  -1作废
     * @param string $property 合同性质id
     * @param string $sortBy 排序字段
     * @param boolean $sortAsc 是否升序
     * @param boolean $property 合同性质
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     * @param string $invoiceType 0 发票 1收据 2发票和收据
     */
    public function actionGetContractList($pageIndex = 1, $pageSize = 10, $sortBy = null, $sortAsc = '',$BusinessType = null, $status = null, $property = null, $keyword = null, $areaId = null, $invoiceType = null, $beginInputDate = null, $endInputDate = null,$isOver = '')
    {
        $signPeopleId = '';
        $user = Yii::$app->user->identity;
        $userEntity = ErpInterfaceService::getUserByCode($user->usercode);
        if ($userEntity->OnlyViewMyself) {
            $signPeopleId = $user->userguid;
        }

        $data = $this->_contractService->getContractList($pageIndex, $pageSize, $sortBy, $sortAsc, $BusinessType,$status, $property, $keyword, $areaId, $invoiceType, $signPeopleId, $beginInputDate, $endInputDate,$isOver);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    public function actionGetContractCaibaoList($pageIndex = 1, $pageSize = 10,$beginInputDate = null, $endInputDate = null){
        $data = $this->_contractService->getContractCaibaoList($pageIndex, $pageSize, $beginInputDate, $endInputDate);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取结算合同列表
     * @param integer $pageIndex 页码
     * @param integer $pageSize 页条数
     * @param string $sortBy 排序字段
     * @param int $status 结算状态 0：未结算 1：已结算
     * @param string $property 合同性质id
     * @param string $sortBy 排序字段
     * @param boolean $sortAsc 是否升序
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     * @param string $beginDate 结算开始时间
     * @param string $endDate 结算结束时间
     */
    public function actionGetBalanceContractList($pageIndex = 1, $pageSize = 10, $sortBy = null, $sortAsc = '',$BusinessType = '', $backstatus = '' , $status = null, $property = null, $keyword = null, $areaId = null, $beginDate = null, $endDate = null)
    {
        $data = $this->_contractService->getBalanceContractList($pageIndex, $pageSize, $sortBy, $sortAsc,$BusinessType, $backstatus, $status, $property, $keyword, $areaId, $beginDate, $endDate);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 导出未结算合同
     * @param boolean $property 合同性质
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     * @param string $beginDate 结算开始时间
     * @param string $endDate 结算结束时间
     */
    public function actionExportBalanceContractListExecl()
    {
        $property = $this->getParam('property', 'post');
        $keyword = $this->getParam('keyword', 'post');
        $areaId = $this->getParam('areaId', 'post');
        $beginDate = $this->getParam('beginDate', 'post');
        $endDate = $this->getParam('endDate', 'post');
        $status = $this->getParam('status', 'post');
        $backstatus = $this->getParam('backstatus', 'post');
        $data = $this->_contractService->exportBalanceContractListExcel($property, $keyword, $areaId, $beginDate, $endDate,$status,$backstatus);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 导入合同结算状态
     */
    public function actionImportBalanceContractListExecl()
    {
        $data = $this->_contractService->importBalanceContractListExecl();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同城市区域列表
     */
    public function actionGetContractAreaList()
    {
        $data = $this->_contractService->getContractAreaList();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同签约区域
     */
    public function actionGetAreaInfo($keyword, $limit){
        $data = $this->_contractService->getAreaInfo($keyword, $limit);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取收入信息数据
     */
    public function actionGetContractRevenue()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {
            $this->errorParam();
        }
        $data = $this->_contractService->getContractRevenue($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取单条收入信息数据
     */
    public function actionGetContractRevenueById()
    {
        $this->exitIfNotPost();
        $oid = $this->getParam('oid', 'post');
        if (empty($oid)) {
            $this->errorParam();
        }
        $data = $this->_contractService->getContractRevenueById($oid);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取收入结转信息数据
     */
    public function actionGetContractCarryoverById()
    {
        $this->exitIfNotPost();
        $oid = $this->getParam('oid', 'post');
        if (empty($oid)) {
            $this->errorParam();
        }
        $data = $this->_contractService->getCarryoverById($oid);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 处理保存收入信息数据
     */
    public function actionSubmitRevenue()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');//合同id
        $revenueList = $this->getParam('revenueList', 'post');//收入信息
        $accountCompanyId = $this->getParam('accountCompanyId', 'post');//帐套公司id
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $this->_contractService->submitRevenue($contractId, $accountCompanyId, $revenueList);
        $data = $this->_contractService->getContractRevenue($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 保存应收信息
     */
    public function actionSaveRevenueInfo(){
        $this->exitIfNotPost();
        $revenueId = $this->getParam('revenueId','post');
        $noconfirmbadamount = $this->getParam('noconfirmbadamount','post');
        $haveconfirmbadamount = $this->getParam('haveconfirmbadamount','post');
        $kingdieverifbadamount = $this->getParam('kingdieverifbadamount','post');
        if (empty($revenueId)) {//是否传值为空
            $this->errorParam();
        }

        $res = $this->_contractService->updateRevenueInfo($revenueId, $noconfirmbadamount, $haveconfirmbadamount,$kingdieverifbadamount);
        $this->exportJson([], $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 保存结转信息
     */
    public function actionSaveRevenueCarryoverInfo(){
        $this->exitIfNotPost();
        $carryoverId = $this->getParam('carryoverId','post');
        $revenueId = $this->getParam('revenueId','post');
        $changeamount = $this->getParam('changeamount','post');
        $changebeforethisperiodconfirmtotalamount = $this->getParam('changebeforethisperiodconfirmtotalamount','post');
        $thisperiodconfirmtotalamount = $this->getParam('thisperiodconfirmtotalamount','post');
        $thisperiodconfirmamount = $this->getParam('thisperiodconfirmamount','post');
        if (empty($carryoverId) || empty($revenueId)) {//是否传值为空
            $this->errorParam();
        }

        $res = $this->_contractService->updateRevenueCarryoverInfo($carryoverId, $revenueId ,$changeamount, $changebeforethisperiodconfirmtotalamount,$thisperiodconfirmtotalamount,$thisperiodconfirmamount);
        $this->exportJson([], $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 保存结算与返款信息
     */
    public function actionUpdateContractAccount()
    {
        $this->exitIfNotPost();
        $postData = \Yii::$app->request->post();//获取所有提交数据
        if (empty($postData) || empty($postData['contractBaseInfo'])) {
            $this->errorParam();
        }
        try{
            $data = $this->_contractService->updateContractAccount($postData['contractBaseInfo'],true);
        }catch (\Exception $e){
            $this->exportJson(false, -1, $e->getMessage());
        }
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取结算与返款信息数据
     */
    public function actionGetContractBalanceInfo()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $data = $this->_contractService->getContractBalanceInfo($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同开通信息
     */
    public function actionGetContractOrganizationInfo()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $data = $this->_contractService->getContractOrganizationInfo($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同业务类型
     */
    public function actionGetBusinessType(){
        $data = $this->_contractService->getBusinessTypeAll();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同性质
     */
    public function actionGetContractNatures()
    {
        $data = $this->_contractService->getContractNatures();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同类别
     */
    public function actionGetContractCategories()
    {
        $data = $this->_contractService->getContractCategories();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同大类
     */
    public function actionGetContractBigClass()
    {
        $data = $this->_contractService->getContractBigClass();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 根据大类id,获取合同小类
     * @param string $bigClassId 大类id
     */
    public function actionGetContractSmallClass($bigClassId = '')
    {
        if (empty($bigClassId)) {//是否传值为空
            $this->errorParam();
        }
        $data = $this->_contractService->getContractSmallClass($bigClassId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 根据关键字，获取产品名称列表
     * @param string $keyword 搜索关键字
     * @param int $limit 返回条数 传空：则全部返回
     */
    public function actionGetProducts($keyword = '', $limit = '')
    {
        $data = $this->_contractService->getProducts($keyword, $limit);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 根据关键字，获取应收款名称列表
     * @param string $keyword 搜索关键字
     */
    public function actionGetReceivableFundName($keyword = '')
    {
        $data = $this->_contractService->getReceivableFundName($keyword);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取款项小类
     */
    public function actionGetFundSmallClass($propertyId = '')
    {
        if (empty($propertyId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->getFundSmallClass($propertyId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 特批授权界面获取合同select2控件下拉选项
     * @param string $keyword 搜索关键字
     * @param string $orgId 租户Id
     * @param string $page 分页
     */
    public function actionGetContractListForSepcialAuthorizeSelect2($keyword, $orgId, $limit)
    {
        $result = $this->_contractService->getContractListForSepcialAuthorizeSelect2($keyword, $orgId, $limit);
        $this->exportJson($result, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 违规合同界面获取合同select2控件下拉选项
     * @param string $keyword 搜索关键字
     * @param string $page 分页
     */
    public function actionGetContractListForViolatedContractSelect2($keyword, $limit)
    {
        $result = $this->_contractService->getContractListForViolatedContractSelect2($keyword, $limit);
        $this->exportJson($result, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取所有核算类型
     */
    public function actionGetBussAccountTypes()
    {
        $data = $this->_contractService->getBussAccountTypes();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同文档信息
     */
    public function actionGetContractDocuments()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }

        $data = $this->_contractService->getContractDocuments($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 保存合同文档信息
     */
    public function actionSaveContractDocuments()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $files = $this->getParam('files', 'post');//获取post 文件数组
        $documents = $this->getParam('documents', 'post');//获取文档信息数组

        $data = $this->_contractService->saveContractDocuments($contractId, $files, $documents);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取客户信息
     * @param string $keyword 搜索关键字
     */
    public function actionGetCustomerInfo($keyword = '')
    {
        $data = $this->_contractService->getCustomerInfo($keyword);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取业绩信息
     */
    public function actionGetSignAchievement()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $data = $this->_contractService->getSignAchievement($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());

    }

    /**
     * 保存业绩修改
     */
    public function actionSaveSignAchievement()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        $signAchievements = $this->getParam('signAchievements', 'post');//签约业绩列表
        $paymentAchievements = $this->getParam('paymentAchievements', 'post');//回款业绩列表
        $drawProjectNumeric = $this->getParam('drawProjectNumeric', 'post');//提成产品数
        $projectNumeric = $this->getParam('projectNumeric', 'post');//项目数
        $achievementRemark = $this->getParam('achievementRemark', 'post');//业绩备注
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $data = $this->_contractService->saveSignAchievement($contractId, $drawProjectNumeric, $signAchievements, $paymentAchievements, $projectNumeric, $achievementRemark);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取最新合同编号
     * @param string $areaCode 区域代码
     * @param string $customerId 客户id
     * @param string $contractCode 合同编号
     */
    public function actionGetContractFlowCode($areaCode = '', $customerId = '', $contractCode = '')
    {
        $data = $this->_contractService->getContractFlowCode($areaCode, $customerId, $contractCode);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 导出合同
     */
    public function actionExportContract()
    {
        ini_set('max_execution_time', 180);
        ini_set('memory_limit', -1);
        set_time_limit(0);
        $status = $this->getParam('status', 'post');     //合同状态  合同状态:0：草稿,1：提交复核,2：已审核  -1作废
        $property = $this->getParam('property', 'post'); //合同性质id
        $keyword = $this->getParam('keyword', 'post');   //关键字
        $areaId = $this->getParam('areaId', 'post');     //区域id
        $businesstype = $this->getParam('BusinessType','post');
        $signPeopleId = '';
        $exporttype = $this->getParam('exportType', 'post');     //区域id
        $data = $this->_contractService->exportContract($status, $property, $keyword, $areaId, $signPeopleId, $exporttype,$businesstype);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 导出釆宝合同
     */
    public function actionExportContractCaibao(){
        $beginInputDate = $this->getParam('beginInputDate', 'post');
        $endInputDate = $this->getParam('endInputDate', 'post');
        if(empty($beginInputDate) || $beginInputDate == 'undefined'){
            $beginInputDate = '';
        }
        if(empty($endInputDate) || $endInputDate == 'undefined'){
            $endInputDate = '';
        }

        $data = $this->_contractService->exportContractCaibao($beginInputDate, $endInputDate);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 导出釆宝充值明细
     */
    public function actionExportContractCaibaoMx(){
        $beginInputDate = $this->getParam('beginInputDate', 'post');
        $endInputDate = $this->getParam('endInputDate', 'post');
        $contract_id = $this->getParam('contract_id', 'post');
        if(empty($beginInputDate) || $beginInputDate == 'undefined'){
            $beginInputDate = '';
        }
        if(empty($endInputDate) || $endInputDate == 'undefined'){
            $endInputDate = '';
        }

        $data = $this->_contractService->exportContractCaibaoMx($contract_id);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    public function actionExportContractCaibaoDetail(){
        $contractid = $this->getParam('contractid','post');
        if(empty($contractid)){
            $this->errorParam();
        }
        $data = $this->_contractService->exportContractCaibaoDetail($contractid);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     *
     */
    public function actionExportCaibaoInvoice(){
        $contractid = $this->getParam('contractid','post');
        if(empty($contractid)){
            $this->errorParam();
        }
        $data = $this->_contractService->exportCaibaoInvoice($contractid);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    public function actionDownExcel()
    {
        $fileName = CacheManage::getExportContract();
        Header("Location: $fileName");
        $this->exportJson($fileName, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 租期即将到期授权提醒
     * @param $expiredDays 过期天数：30、60
     * @return array|\yii\db\ActiveRecord[]
     */
    public function actionAuthorizationExpiredRemind()
    {
        $expiredDays = $this->getParam('expiredDays');
        $this->_contractService->authorizationExpiredRemind($expiredDays);
    }

    /**
     * 我的合同
     * @param integer $pageIndex 页码
     * @param integer $pageSize 页条数
     * @param string $sortBy 排序字段
     * @param int $status 合同状态  合同状态:0：草稿,1：提交复核,2：已审核  -1作废
     * @param string $property 合同性质id
     * @param string $sortBy 排序字段
     * @param boolean $sortAsc 是否升序
     * @param boolean $property 合同性质
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     */
    public function actionGetMyContractList($pageIndex = 1, $pageSize = 10, $sortBy = null, $sortAsc = '', $status = null, $property = null, $keyword = null, $areaId = null)
    {
        $signPeopleId = Yii::$app->user->identity->userguid;
        $data = $this->_contractService->getContractList($pageIndex, $pageSize, $sortBy, $sortAsc, $status, $property, $keyword, $areaId, $signPeopleId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 导出合同
     */
    public function actionExportMyContract()
    {
        ini_set('max_execution_time', 180);
        set_time_limit(180);
        $status = $this->getParam('status', 'post');     //合同状态  合同状态:0：草稿,1：提交复核,2：已审核  -1作废
        $property = $this->getParam('property', 'post'); //合同性质id
        $keyword = $this->getParam('keyword', 'post');   //关键字
        $areaId = $this->getParam('areaId', 'post');     //区域id
        $signPeopleId = Yii::$app->user->identity->userguid;
        $data = $this->_contractService->exportContract($status, $property, $keyword, $areaId, $signPeopleId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取所有供应商
     */
    public function actionGetContractSuppliers()
    {
        $data = $this->_contractService->getContractSuppliers();

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 根据供应商名字获取供应商信息
     */
    public function actionGetSupplierInfo()
    {
        $supplier_name = $this->getParam('supplier_name', 'GET');

        $data = $this->_contractService->getSupplierInfoByName($supplier_name);

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取业务类型信息
     */
    public function actionGetBusinessTypeInfo()
    {
        $business_type = $this->getParam('business_type', 'get');

        $data = $this->_contractService->getBusinessTypeInfoByName($business_type);

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取业务类型对应的产品类型
     */
    public function actionGetProductType()
    {
        $businessTypeName = $this->getParam('businessTypeName', 'get');

        if (empty($businessTypeName)) {
            $this->exportJson([], '0', 'fail');
        }

        $productType = \Yii::$app->params['business_product_type'][$businessTypeName];

        $this->exportJson($productType, '0', 'success');
    }

    /**
     * 获取可确认回款合同列表
     * @param int $payway 支付方式(支付宝/微信/全部)
     * @param string $keyword 关键字(支付账户/账号/金额)
     * @param string $product_type 产品类型(全部/移动工程协同/采宝/供应商会员/考察报告/供应商线下活动)
     * @param integer $pageIndex 页码
     * @param integer $pageSize 页条数
     * @param string $sortBy 排序字段
     * @param string $sortBy 排序字段
     * @param boolean $sortAsc 是否升序
     * @param string $beginDate 开始时间
     * @param string $endDate 结束时间
     */
    public function actionGetConfirmContractList($payway = '', $keyword = '', $product_type = '', $pageIndex = 1, $pageSize = 10, $sortBy = null, $sortAsc = '', $beginDate = null, $endDate = null)
    {
        //$data = $this->_contractService->getBalanceContractList($pageIndex, $pageSize, $sortBy, $sortAsc, '', '', '', '', $beginDate, $endDate);
        //$this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());

        $params = [
            'pay_way'   => $this->getParam('pay_way', 'get'),
            'product_name'  => $this->getParam('product_name', 'get'),
            'refund_status' => $this->getParam('refund_status', 'get'),
            'beginDate'     => $this->getParam('beginDate', 'get'),
            'endDate'       => $this->getParam('endDate', 'get'),
            'keyword'       => $this->getParam('keyword', 'get'),
            'pageIndex'     => $this->getParam('pageIndex', 'get'),
            'pageSize'      => $this->getParam('pageSize', 'get')
        ];
        $params['beginDate'] = $params['beginDate'] . ' 00:00:00';
        $params['endDate'] = $params['endDate'] . ' 23:59:59';

        $data = $this->_contractService->getPayinfoLists($params);

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 导出供应商线下收款信息 导入模版
     */
    public function actionExportSupplierPaymentModel()
    {
        $head = array('报名人', '公司', '是否认证', '是否金牌', '支付金额', '扣减权益',
            '权益订单号', '支付方式', '报名时间', '发票代码');

        ExcelManage::responseToExcel([], $head, 11, '供应商收款信息导入模版');
        exit();
    }

    /**
     * 导入供应商收入信息
     * import-invoice-list-execl
     */
    public function actionImportSupplierPaymentListExecl()
    {
        $contract_id = $this->getParam('contract_id', 'GET');
        $data = $this->_contractService->importSupplierPaymentListExecl($contract_id);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    public function actionExportInvoiceModel()
    {
        $head = array('发票类别', '发票代码', '发票类型', '发票编号', '申请人', '客户名称', '开票单位',
            '开票金额', '开票时间');

        ExcelManage::responseToExcel([], $head, 9, '供应商发票信息导入模版');
        exit();
    }

    /**
     * 导入发票
     * import-invoice-list-execl
     */
    public function actionImportInvoiceListExecl()
    {
        $contract_id = $this->getParam('contract_id', 'GET');
        $data = $this->_contractService->importInvoiceListExecl($contract_id);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 导出待确认回款支付列表
     */
    public function actionExportConfirmPaymentList()
    {
        $head = array(
            'product_name'  => '商品名称',
            'pay_way'       => '支付方式',
            'pay_amount'    => '支付金额',
            'pay_time'      => '支付时间',
            'order_code'    => '支付订单号',
            'refund_status' => '是否已确认回款'
        );

        $params = [
            'pay_way'   => $this->getParam('pay_way', 'post'),
            'product_name'  => $this->getParam('product_name', 'post'),
            'refund_status' => $this->getParam('refund_status', 'post'),
            'beginDate'     => $this->getParam('beginDate', 'post'),
            'endDate'       => $this->getParam('endDate', 'post'),
            'keyword'       => $this->getParam('keyword', 'post'),
            'pageIndex'     => $this->getParam('pageIndex', 'post'),
            'pageSize'      => $this->getParam('pageSize', 'posts')
        ];

        $params['beginDate'] = $params['beginDate'] . ' 00:00:00';
        $params['endDate'] = $params['endDate'] . ' 23:59:59';
        //$params['refund_status'] = empty($params['refund_status']) ? '0' : $params['refund_status'];

        $data = $this->_contractService->getPayinfoLists($params);

        $list = $data['items'];

        foreach ($list as &$li) {
            $li['refund_status'] = $li['refund_status'] == 0 ? '否' : '是';
        }

        ExcelManage::responseToExcel($list, $head, 6, '供应商收款信息导出列表');
        exit();
    }

    /**
     * 获取业务类型编号
     */
    public function actionGetContractTypes()
    {
        $result = \Yii::$app->params['contract_types'];

        $this->exportJson($result, 0, 'success');
    }

    public function actionGetWithdrawFeeRate(){
        $result = \Yii::$app->params['withdraw_fee_rate'];

        $this->exportJson($result, 0, 'success');
    }

    /**
     * 保存交付信息
     */
    public function actionSavePayover(){
        $editmode = $this->getParam("editmode","post");
        $oid = $this->getParam("oid","post");
        $contractid = $this->getParam("contractid","post");
        $contractcode = $this->getParam('contractcode','post');
        $applicationname = $this->getParam("applicationname","post");
        $begintime = $this->getParam("begintime","post");
        $endtime = $this->getParam("endtime","post");
        if(empty($contractid) || empty($editmode) || ($editmode!='1' && $editmode!='2')){
            $this->errorParam();
        }

        $result = $this->_contractService->savePayoverinfo($editmode,$oid,$contractid,$contractcode,$applicationname,$begintime,$endtime);
        if($result){
            $this->exportJson($result, 0, '保存成功!');
        }else{
            $this->exportJson([], 1, '保存数据出错!');
        }
    }

    /**
     * 保存交付信息Saas类
     */
    public function actionSavePayoverSaas(){
        $oid = $this->getParam("oid","post");
        $tenantname = $this->getParam("tenantname","post");
        $tenantcode = $this->getParam("tenantcode","post");
        $authorizeperiod = $this->getParam("authorizeperiod","post");
        if(empty($authorizeperiod)){
            $this->exportJson([], -1, '租期必须填写!');
        }

        $result = $this->_contractService->savePayoverSaasInfo($oid,$tenantname,$tenantcode,$authorizeperiod);
        if($result){
            $this->exportJson([], 0, '保存成功!');
        }else{
            $this->exportJson([], -1, '保存数据出错!');
        }
    }

    /**
     * 保存交付结算信息
     */
    public function actionSavePayoverBalance(){
        $this->exitIfNotPost();
        $postData = \Yii::$app->request->post();//获取所有提交数据
        if (empty($postData) || empty($postData['contractBaseInfo']) || empty($postData['balancedata'])) {
            $this->errorParam();
        }

        //先保存结算信息,然后做保存合同信息及生成出库等操作

        try{
            $result = $this->_contractService->savePayoverBalanceinfo($postData['balancedata']);

            $result = $this->_contractService->updateContractAccount($postData['contractBaseInfo']);
        }catch (\Exception $e){
            $this->exportJson(false, -1, $e->getMessage());
        }

        if($result){
            $this->exportJson($result, 0, '保存成功!');
        }else{
            $this->exportJson([], 1, '保存数据出错!');
        }
    }

    /**
     * 下载纸质合同存入信息导入模板
     */
    public function actionDownloadContractDocStoreTemplate()
    {
        $docService = new DocumentService();
        $data = $docService->downloadContractDocStoreTemplate();
        $this->exportJson($data, $docService->getErrCode(), $docService->getErrMsg());
    }

    /**
     * 导入纸质合同存放信息
     */
    public function actionImportContractDocStore()
    {
        $this->exitIfNotPost();
        $uploadInfo = $_FILES['file'];
        $ext = strtolower(pathinfo($uploadInfo['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['xls', 'xlsx'])) {
            $this->exportJson(false, '', '文件类型不被允许');
        }
        $uploadFileName = $uploadInfo['tmp_name'];
        $docService = new DocumentService();
        $data = $docService->importContractDocStore($uploadFileName, $ext);
        $this->exportJson($data, $docService->getErrCode(), $docService->getErrMsg());
    }

    /**
     * 删除交付信息
     */
    public function actionDeletePayover(){
        $oid = $this->getParam("oid","post");
        $contractid = $this->getParam("contractid","post");
        if(empty($contractid) || empty($oid)){
            $this->errorParam();
        }
        $result = $this->_contractService->deletePayoverinfo($oid,$contractid);
        if($result){
            $this->exportJson($result, 0, 'success!');
        }else{
            $this->exportJson([], 1, '删除失败!');
        }
    }

    /**
     * 按照关键字搜索供应商
     */
    public function actionSearchSupplierByKey(){
        $keyword = $this->getParam('keyword','post');
        if(empty($keyword)){
            $this->errorParam();
        }
        $result = $this->_contractService->searchSuppliersByKey($keyword);
        if($result){
            $this->exportJson($result, 0, 'success!');
        }else{
            $this->exportJson([], 1, '查询不到符合条件数据!');
        }
    }

    public function actionSetOverContract(){
        $contractid = $this->getParam('contractid','post');
        $status = $this->getParam('overstatus','post');
        if(empty($contractid)){
            $this->errorParam();
        }
        $result = $this->_contractService->setOverStatusContract($contractid,$status);
        if($result){
            $this->exportJson($result, '0', 'success!');
        }else{
            $this->exportJson([], '1', '更新失败!');
        }
    }

    public function actionSaveContractSuppliersPayment(){
        $paymentInfo = $this->getParam('paymentInfo','post');
        if(empty($paymentInfo)){
            $this->errorParam();
        }
        $result = $this->_contractService->saveContractSuppliersPayment($paymentInfo);
        if($result){
            $this->exportJson($result, '0', 'success!');
        }else{
            $this->exportJson([], '1', '更新失败!');
        }
    }

    /**
     * 返款信息保存
     */
    public function actionSaveBackAmount(){
        $contractid = $this->getParam('contractid','post');
        $backrecord = $this->getParam('backrecord','post');
        if(empty($backrecord) || empty($contractid)){
            $this->errorParam();
        }
        $result = $this->_contractService->saveContractBackAmount($backrecord,$contractid);
        if($result){
            $this->exportJson($result, '0', 'success!');
        }else{
            $this->exportJson([], '1', '更新失败!');
        }
    }

    public function actionDeleteBackAmount(){
        $contractid = $this->getParam('contractid','post');
        $backamountid = $this->getParam('back_amount_id','post');
        if(empty($backamountid) || empty($contractid)){
            $this->errorParam();
        }
        $result = $this->_contractService->deleteContractBackAmount($backamountid,$contractid);
        if($result){
            $this->exportJson($result, '0', 'success!');
        }else{
            $this->exportJson([], '1', '更新失败!');
        }
    }

    /**
     * 标的物同步至合同系统接口
     */
    public function actionAddDocumentInfo(){
        $docs = $this->getDocumentParams();
        $result = $this->_contractService->doSyncDocument($docs);
        $this->exportJson($result, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }


    /**
     * 标的物同步至合同系统接口数据格式化
     * @return array
     */
    private function getDocumentParams(){
        $filesData = Yii::$app->request->request('FileList');
        $filesList = json_decode($filesData,true);
        $collections = array();
        foreach ($filesList as $files){
            $document = array();
            $document['document_id'] = $files['FileGUID'];
            $document['document_name'] = $files['FileName'];
            $document['document_ext_name'] = '标的物';
            $document['document_path'] = $files['NetWorkUrl'];
            $document['business_id'] = $files['ContractGUID'];
            $document['created_by'] = $files['CreatorName'];
            $document['created_on'] = $files['CreateTime'];
            $document['out_file_id'] = $files['OutFileID'];
            $document['creator_id'] = $files['CreatorGUID'];
            $document['recipient_id'] = $files['ReceiveUserGUID'];
            $document['received_by'] = $files['ReceiveUser'];
            $document['received_on'] = $files['ReceiveDate'];
            $document['is_sign'] = $files['IsSignName'];
            $document['contract_code'] = $files['ContractCode'];
            $document['document_old_name'] = $files['FileOldName'];
            $document['document_new_name'] = $files['FileNewName'];
            $document['opportunities_id'] = $files['OpportunitiesGUID'];
            $document['document_size'] = $files['FileSize'];
            $document['document_group'] = $files['FileGroup'];
            $document['bop_file_type'] = $files['BopFileType'];
            $collections[] = $document;
        }
        return $collections;
    }
}
